use serde::{Deserialize, Serialize};

/// 抽象分页参数对象
/// [`BasePage::get_page_data()`]  获取PageData数据 需要手动实现
/// Unlike [`BasePage::check_page_data()`] 校验分页数据并生成默认分页
/// Unlike [`BasePage::get_order_type()`] 获取排序类型 asc或desc
pub trait BasePage {
    fn get_page_data(&self) -> PageData;
    fn check_page_data(&self) -> PageData {
        self.get_page_data().check()
    }
    fn get_order(&self) -> Option<Sorter> {
        self.get_page_data().sorter
    }
    fn get_order_type(&self) -> sea_orm::Order {
        if let Some(sorter) = self.get_page_data().sorter {
            sorter.order()
        } else {
            sea_orm::Order::Asc
        }
    }
}

#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct PageData {
    pub page: u64,
    pub page_size: u64,
    pub sorter: Option<Sorter>,
}

impl PageData {
    pub fn check(self) -> PageData {
        PageData {
            page: if self.page <= 0 { 1 } else { self.page },
            page_size: if self.page_size <= 0 {
                10
            } else {
                self.page_size
            },
            sorter: self.sorter,
        }
    }
}

#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct PageResult<T> {
    pub page: u64,
    pub page_size: u64,
    pub total: u64,
    pub record: Vec<T>,
}

#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct Sorter {
    pub field: String,
    pub direction: String,
}

impl Sorter {
    pub fn order(self) -> sea_orm::Order {
        match self.direction.as_str() {
            "asc" => sea_orm::Order::Asc,
            "desc" => sea_orm::Order::Desc,
            _ => sea_orm::Order::Desc,
        }
    }
}
